package com.example.web.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.web.mapper.CategoryMapper;
import com.example.web.service.CategoryService;
import com.example.xo.pojo.Category;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public boolean add(Category category) {
        //调用方法
        medo();
       //雪花id
        String snowflakeNextIdStr = IdUtil.getSnowflakeNextIdStr();
        category.setCategoryId(snowflakeNextIdStr);
        //返回int类型 如果有变动就说明添加成功
        int insert = categoryMapper.insert(category);
        return insert>0;
    }
    @Override
    public boolean update(Category category) {
        //调用方法
        medo();
        LambdaQueryWrapper<Category>wrapper=new LambdaQueryWrapper<>();
        wrapper.isNull(Category::getDeleted);
        wrapper.eq(Category::getCategoryId,category.getCategoryId());
        int update = categoryMapper.update(category,wrapper);
        return update>0;
    }

    @Override
    public boolean deleteById(String id) {
        //调用findById的方法，封装为对象
        Category category=findById(id);
        //将删除的额时间修改为现在的时间
        category.setDeleted(LocalDateTime.now());
        //删除是用软删除，所以使用updateById的方法
        int i = categoryMapper.updateById(category);
        //表示有改动的行数
        return i>0;
    }

    @Override
    public List<Category> findAll() {
        LambdaQueryWrapper<Category>wrapper=new LambdaQueryWrapper<>();
        wrapper.isNull(Category::getDeleted);
        List<Category> categories = categoryMapper.selectList(wrapper);
        return categories;
    }

    @Override
    public Category findById(String id) {
        LambdaQueryWrapper<Category>wrapper=new LambdaQueryWrapper<>();
        wrapper.isNull(Category::getDeleted);
        wrapper.eq(Category::getCategoryId,id);
        Category category = categoryMapper.selectOne(wrapper);
        return category;


    }

    @Override
    public Category findByName(String name) {
        LambdaQueryWrapper<Category>wrapper=new LambdaQueryWrapper<>();
        wrapper.isNull(Category::getDeleted);
        wrapper.eq(Category::getCategoryName,name);

        return  categoryMapper.selectOne(wrapper);
    }
    private boolean medo() {
        Category category = new Category();
        Category byName = findByName(category.getCategoryName());
        //如果返回的值不是null就代表有重复，返回false
        if (byName != null) {
            log.info("分类{}", category.getCategoryName());
            return false;
        }
        return true;
    }
}
